/*
 * Created on Jan 8, 2009
 */
package ak.salmon.markup;

import java.util.Stack;

/**
 * Provides low level xml drawing functions.
 * 
 * @author albert_kwong
 */
public class MarkupWriter {

    private StringBuilder buf;
    private Stack<String> stack;
    private boolean appendAttr = false;

    public MarkupWriter() {
        this.buf = new StringBuilder();
        this.stack = new Stack<String>();
    }

    public MarkupWriter element(String element, String... attributes) {

        assert attributes.length % 2 == 0 : "Expecting even number of attribute-value pairs.";

        stack.push(element);
        buf.append("<").append(element).append(" ");
        for (int i = 0; i < attributes.length; i += 2) {
            buf.append(attributes[i]).append("='").append(attributes[i + 1]).append("' ");
        }
        buf.append(">");
        appendAttr = true;
        return this;
    }

    public MarkupWriter attribute(String attr, int x) {
        return attribute(attr, x + "");
    }

    public MarkupWriter attribute(String attr, String value) {

        assert appendAttr : "Cannot append attribute at this point.";

        int l = buf.length();
        buf.replace(l - 1, l, "");
        buf.append(attr).append("='").append(value).append("' ");
        buf.append(">");

        return this;
    }

    public MarkupWriter cdata(String data) {
        appendAttr = false;
        buf.append(data);
        return this;
    }

    public MarkupWriter end() {
        appendAttr = false;
        String element = stack.pop();
        buf.append("</").append(element).append(">\n");
        return this;
    }

    public String toString() {
        return buf.toString();
    }
}
